package com.koron.common.core.feignConfig;

import cn.hutool.aop.ProxyUtil;
import com.alibaba.fastjson.JSON;
import com.koron.bean.base.Response;
import feign.FeignException;
import feign.Request;
import feign.Target;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @ClassName FeignFallbackFactory
 * @description
 * @Author zhouj
 * @Date 2021/11/2 10:20
 */
@Slf4j
@Component
public class FeignFallbackFactory<T> extends ExtFallbackFactory<T> {

    @Override
    public T create(Method method, Throwable cause) {
        return createFallbackService(cause, method.getDeclaringClass());
    }

    private T createFallbackService(Throwable ex, Class<?> targetClass) {

        FeignException.InternalServerError ex1 = (FeignException.InternalServerError) ex;

        String responseBody = ex1.contentUTF8();

        return toResponse(responseBody, ex1.request());
        // 创建一个JDK代理类
        //return ProxyUtil.newProxyInstance((proxy, method, args) -> Response.fail(ex.getMessage()), targetClass);
    }

    private T toResponse(String respMsg, Request request) {
        Target<?> target = request.requestTemplate().feignTarget();
        Class<?> targetClazz = target.type();
        String serviceName = target.name();
        return ProxyUtil.newProxyInstance((proxy, method, args) -> JSON.parseObject(respMsg, Response.class), targetClazz);
    }
}
